<template>
  <div :class="className" :style="{ height: height, width: width}" :id="chartOption.bindingDiv" ref="text">
  
     <video :id="'player'+chartOption.bindingDiv" :style="{ height: height, width: width }" :controls="this.chartOption.controls"  autoplay muted>
    </video>
  </div>
</template>

<script>

import resize from '@/views/dashboard/mixins/resize'
import flvjs from 'flv.js'
import '../../animate/animate.css'
import {videoPlayer} from 'vue-video-player';
import 'videojs-flash'
import videojs from 'video.js'
import 'video.js/dist/video-js.css'
import 'vue-video-player/src/custom-theme.css'
import { chartApiBar } from "@/api/tool/datav/chartApi";
import { websocketCommand } from "../../util/websocket.js";

import {parseQueryString, fIsUrL} from '../../util/urlUtil'


const animationDuration = 6000;

export default {
  components: {
    videoPlayer,
  },
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    chartOption: {
      type: Object,
    }
  },
  data() {
    return {
      flvPlayer:null,
      chart: null,
      dataOption: this.chartOption,
      playerOptions: {
       playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
          autoplay: false, // 如果为true,浏览器准备好时开始回放。
          muted: false, // 默认情况下将会消除任何音频。
          loop: false, // 是否视频一结束就重新开始。
          preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
          language: "zh-CN",
          aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          // sources: [
          //     // {
          //     //     type: "video/mp4", // 类型
          //     //     src: "https://v-cdn.zjol.com.cn/280443.mp4" // url地址
          //     // },
              
          //   {
          //     type: 'application/x-mpegURL',
          //     src: 'http://open.ys7.com/v3/openlive/732526258_1_2.m3u8?expire=1694759188&id=492340778362732544&t=c0eea7db4fd9fd2f2f48b630566d99fd73c241da9b8e0e51286997c023d7666e&ev=100', //你的m3u8地址（必填）
          //   },
          //   // {
          //   //   type: 'application/x-mpegURL',
          //   //   src: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-uni4934e7b/c4d93960-5643-11eb-a16f-5b3e54966275.m3u8', //你的m3u8地址（必填）
          //   // },
          // ],
          techOrder: ['flash', 'html5'], // 兼容顺序
          sourceOrder: true, // 
          flash: { hls: { withCredentials: false } },
          html5: { hls: { withCredentials: false } },
          sources: [{ // 流配置，数组形式，会根据兼容顺序自动切换
            type: 'rtmp/mp4',
            src: 'rtmp://https://rtmp01open.ys7.com:9188/v3/openlive/732526258_1_1.flv?expire=1695015291&id=493414950673321984&t=5983f40d2a710ef9663eb74a47d785f6ef2636fec12e69babfbaa718028f2f63&ev=100'
          }, {
            withCredentials: false,
            type: 'application/x-mpegURL',
            src: 'http://open.ys7.com/v3/openlive/732526258_1_2.m3u8?expire=1694759188&id=492340778362732544&t=c0eea7db4fd9fd2f2f48b630566d99fd73c241da9b8e0e51286997c023d7666e&ev=100', //你的m3u8地址（必填）
          }],
          hls: true,
          poster: "", // 封面地址
          notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
          controlBar: {
              timeDivider: true, // 当前时间和持续时间的分隔符
              durationDisplay: true, // 显示持续时间
              remainingTimeDisplay: false, // 是否显示剩余时间功能
              fullscreenToggle: true // 是否显示全屏按钮
          },
      },
      timer: "",
      wsObj: null,
      wsFlag: false,
      wsTimer: "",
      wsValue: null,
      animate: this.className
      
    };
  },
  watch: {
    width() {
      
    },
    height() {
      
    },
    chartOption: {
      deep: true,
      handler(newVal) {
        this.setOptions(JSON.parse(JSON.stringify(newVal)));
      }
    },
    "chartOption.timeout": {
      handler() {
        this.chart = null;
        this.initChart();
      }
    },
    "chartOption.dataSourceType": {
      handler(value) {
        //切换数据源重新连接
        if (value !== "websocket") {
          this.wsFlag = false;
          //每次切换数据源恢复原来动画
          this.animate = this.className;
        }
        if (value !== "url") {
          clearTimeout(this.timer);
        } 
      }
    },
    "chartOption.interfaceKey": {
      handler(newValue, oldValue) {
        //初始化不创建连接，改变接口地址重新创建
        if (oldValue !== undefined && oldValue != "") {
          this.wsValue = null;
          this.closeWs();
          this.createWs();
          this.animate = this.className;
        }
      }
    },
    wsFlag: {
      handler(value) {
        if (!value) {
          this.wsValue = null;
          this.closeWs();
        }
      }
    },
    className: {
      handler(value) {
        this.animate = value;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (this.flvPlayer) {
      this.flvPlayer.destroy();
    }
    clearTimeout(this.timer);
    if (this.wsFlag) {
      this.closeWs();
    }
  },
  methods: {
    initChart() {
      
      
      if (this.timer != "") {
        clearTimeout(this.timer);
      }
      if (
        (this.chartOption.dataSourceType == 'url' || this.chartOption.dataSourceType == 'database') &&
        this.chartOption.timeout > 0
      ) {
        let timerTask = () => {
          this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
          this.timer = setTimeout(() => {
           
            timerTask();
          }, this.chartOption.timeout);
        };

        timerTask();
      }else{
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
      
    },
    setOptions: async function(dataOption) {
      if (dataOption.dataSourceType == "url" || dataOption.isStaticData == false) {
        let paramJson = parseQueryString(dataOption.requestParameters);

        let interfaceURL = dataOption.interfaceURL;

        let result = await chartApiBar(
          dataOption.requestMethod,
          interfaceURL,
          paramJson,
          dataOption.token
        );
        if(result != undefined){
          dataOption.videoURL = result;
        }
        

      } else if (dataOption.dataSourceType == "database") {
      } else if (dataOption.dataSourceType == "websocket") {
        if (
          dataOption.interfaceKey != undefined &&
          dataOption.interfaceKey != ""
        ) {
          if (!this.wsFlag) {
            this.wsFlag = true;
            this.wsValue = null;
            this.createWs();
          }
          if (this.wsValue != null) {
            dataOption.videoURL = this.wsValue;
          }
        }
      }
      //数据处理
       if(dataOption.customData != undefined && dataOption.customData != ""){
          
          try {
             dataOption.videoURL = (
          
              //里面为要处理的代码块
            eval(dataOption.customData) 
            
            )(
              dataOption.videoURL,
              this.$refs.text
            );
          } catch (error) {
            console.log(error)
          }
         
       }
      //交互组件配置
       if(dataOption.interactData != undefined && dataOption.interactData != ""){
          
          try {
             dataOption.videoURL = (
          
              //里面为要处理的代码块
            eval(dataOption.interactData) 
            
            )(
              dataOption.videoURL,
              this.$refs.text
            );
          } catch (error) {
            console.log(error)
          }
         
       }

      //销毁播放器
      if (this.flvPlayer) {
        
        this.flvPlayer.destroy();
        
      }
      this.flvPlayer = null;
      //   //视频地址
      //   this.$refs.video.src = dataOption.videoURL;
      //   this.$refs.video.loop = dataOption.replay;
      //   // //自动播放
      //   this.$refs.video.play()


      
      //用video-player切换播放源
      //响应成功的数据中提取url赋值给变量url
　　　//this.playerOptions['sources'][0]['src'] = this.chartOption.videoURL;
     

      // videojs.options.flash.swf = 'https://cdn.bootcss.com/videojs-swf/5.4.1/video-js.swf';
      //   this.player = videojs('player'+this.customId); //my-player为页面video元素的id
      //   this.player.src([{
      //       type: 'application/x-mpegURL',
      //       src: this.chartOption.videoURL
      //     }])
      //   this.player.play(); //播放
      if (flvjs.isSupported()) {

        if(dataOption.videoURL != ""){
            var videoElement = document.getElementById('player'+dataOption.bindingDiv);
            this.flvPlayer = flvjs.createPlayer({
                type: 'flv',
                isLive: true,
                hasAudio: false,
                url: dataOption.videoURL		// 自己的flv视频流
              },{
                // 其他的配置项可以根据项目实际情况参考 api 去配置
                autoCleanupMinBackwardDuration: true, // 清除缓存 对 SourceBuffer 进行自动清理
              });
              this.flvPlayer.attachMediaElement(videoElement);
              this.flvPlayer.load();
              this.flvPlayer.play();

              this.flvPlayer.on(flvjs.Events.ERROR, (errType, errDetail) =>{
                // todo
                this.destroyVideos()
              }) 
        }
        

      }
      // console.log(dataOption.videoURL)
      // let vdo = document.getElementById("player"+this.customId)
      // vdo.src=dataOption.videoUR;
      // vdo.play();
      // console.log(this.$refs.video)

      // let myvideo = videojs('player'+this.customId, {
      //               bigPlayButton: false,
      //               textTrackDisplay: false,
      //               posterImage: true,
      //               errorDisplay: false,
      //               controlBar: true
      //           }, function () {
      //               this.play()
      //           })
      // myvideo.dispose()

    },
    destroyVideos(){
      if(!this.flvPlayer) return
      this.flvPlayer.pause()
      this.flvPlayer.unload()
      this.flvPlayer.detachMediaElement()
      this.flvPlayer.destroy()
      this.flvPlayer = null
    },
//  ws连接成功，后台返回的ws数据
    receiveMsg(e) {
      if (e.action == "chat") {
        // console.log('服务端推送',e);
        this.wsValue = e.result;
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
    },
    // 建立连接、发起ws请求，以心跳方式，向服务端发送数据
    createWs() {
      this.wsObj = new WebSocket(process.env.VUE_APP_WEBSOCKET);
      // 若为对象类型，以回调方式发送
      websocketCommand(
        this.wsObj,
        "create",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
    },
    // 断网重连，需要处理的逻辑
    reconnectWs() {
      if (this.wsObj) {
        console.log("%c websocket_reconnect", "color:blue");
        this.createWs();
      }
    },
    // 以回调方式向服务端发送(对象类型的)心跳
    sendHeartBeat() {
      if (this.wsTimer != "") {
        clearTimeout(this.wsTimer);
      }

      let wsTimerTask = () => {
        console.log("发送心跳", "ping");
        let obj = { action: "keep", key: this.chartOption.interfaceKey };
        this.wsObj.send(JSON.stringify(obj));
        this.wsTimer = setTimeout(() => {
          wsTimerTask();
        }, parseInt(process.env.VUE_APP_WEBSOCKET_TIMEOUT));
        this.wsWarning();
      };

      wsTimerTask();
    },
    wsWarning() {
      //如果断开连接则显示组件警告动画并清除计数器
      if (this.wsObj.readyState == 3) {
        this.animate = "warning";
        clearTimeout(this.wsTimer);
      }
    },
    closeWs() {
      clearTimeout(this.wsTimer);
      websocketCommand(
        this.wsObj,
        "close",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
      this.wsObj = null;
    }, 
  }
};
</script>
